package me.jessyan.armscomponent.app.mvp.ui.activity.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.ArmsUtils;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import me.jessyan.armscomponent.app.app.UserConstants;
import me.jessyan.armscomponent.commonres.widget.toast.ToastView;
import me.jessyan.armscomponent.commonsdk.core.User;
import me.jessyan.armscomponent.commonres.utils.ProgressDialogUtil;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import me.jessyan.armscomponent.app.R;
import me.jessyan.armscomponent.app.di.component.DaggerUserLoginComponent;
import me.jessyan.armscomponent.app.mvp.contract.user.UserLoginContract;
import me.jessyan.armscomponent.app.mvp.presenter.user.UserLoginPresenter;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * <p>
 * Author: Taozebi
 * Date: 08/08/2021 15:36
 * Description: 用户登录
 */

@Route(path = RouterHub.USER_LOGINACTIVITY)
public class UserLoginActivity extends BaseActivity<UserLoginPresenter> implements UserLoginContract.View {


    @BindView(R.id.user_btn_login1)
    Button user_btn_login1;

    @BindView(R.id.user_ll_verification)
    LinearLayout user_ll_verification;
    @BindView(R.id.user_ll_password)
    LinearLayout user_ll_password;
    @BindView(R.id.user_tv_login_ver_code)
    TextView user_tv_login_ver_code;


    @BindView(R.id.user_et_login_username)
    EditText user_et_login_username;
    @BindView(R.id.user_et_login_password)
    EditText user_et_login_password;
    @BindView(R.id.user_et_login_ver_code)
    EditText user_et_login_ver_code;

    @BindView(R.id.user_tv_ver_code_login)
    TextView user_tv_ver_code_login;
    @BindView(R.id.user_tv_password_login)
    TextView user_tv_password_login;

    @BindView(R.id.user_spinner_code)
    Spinner user_spinner_code;

    @BindView(R.id.cb_password)
    CheckBox cb_password;

    @BindView(R.id.user_iv_login_image_code)
    ImageView user_iv_login_image_code;
    @BindView(R.id.user_et_login_image_code)
    EditText user_et_login_image_code;

    private ImageLoader mImageLoader;

    private boolean isPasswordLogin = true;
    private String username = "15102727731";
    private String password = "123456";
    private String phonePreff = "";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerUserLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.user_activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        getParams();
        initSpinner();
        isPasswordLogin(isPasswordLogin);
        user_et_login_username.setText(username);
        user_et_login_password.setText(password);

        mImageLoader = ArmsUtils.obtainAppComponentFromContext(this).imageLoader();
        mPresenter.imgCaptcha();
    }

    public void getParams(){
        Intent intent = getIntent();
        if(intent.hasExtra("isPasswordLogin")) {
            isPasswordLogin = intent.getBooleanExtra("isPasswordLogin", false);
            username = getIntent().getStringExtra(UserConstants.USER_NAME);
            password = getIntent().getStringExtra(UserConstants.PASSWORD);
        }
    }

    @OnCheckedChanged({R.id.cb_password})
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.cb_password:
                if (isChecked) {
                    //从密码不可见模式变为密码可见模式
                    user_et_login_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //从密码可见模式变为密码不可见模式
                    user_et_login_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
        }
    }

    @Override
    public void showLoading() {
        ProgressDialogUtil.show(this,"","加载中...");
    }

    @Override
    public void hideLoading() {
        ProgressDialogUtil.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ToastView.getInstance().showToast(this,message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.user_tv_register,R.id.user_iv_login_image_code,R.id.user_tv_login_ver_code,R.id.user_btn_login1,R.id.user_tv_login_forget_password,R.id.user_tv_password_login,R.id.user_tv_ver_code_login})
    public void onClicked(View v) {
        int id = v.getId();
        if (id == R.id.user_tv_register) {
            if (Utils.isFastClick()) {
                toRegister();
            }
        }else if (id == R.id.user_iv_login_image_code) {
            if (Utils.isFastClick()) {
                mPresenter.imgCaptcha();
            }
        } else if(id == R.id.user_tv_login_ver_code){
            if (Utils.isFastClick()) {
                mPresenter.checkMobile();
            }
        }else if (id == R.id.user_btn_login1) {
            if (Utils.isFastClick()) {
                mPresenter.login();
            }
        }else if(id == R.id.user_tv_login_forget_password){
            if (Utils.isFastClick()) {
                toForgetPassword();
            }
        }else if (id == R.id.user_tv_ver_code_login) {
            isPasswordLogin(false);
        } else if (id == R.id.user_tv_password_login) {
            isPasswordLogin(true);
        }
    }

    private void initSpinner() {
        String[] countryCodeArray = getResources().getStringArray(R.array.public_CountryCodes);
        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(this, R.layout.layout_item_select, countryCodeArray);
        //设置数组适配器的布局样式
        starAdapter.setDropDownViewResource(R.layout.layout_item_drapdown);
        //从布局文件中获取名叫sp_dialog的下拉框
        Spinner sp = findViewById(R.id.user_spinner_code);
        //设置下拉框的标题，不设置就没有难看的标题了
        sp.setPrompt("选择国家代码");
        //设置下拉框的数组适配器
        sp.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        sp.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        sp.setOnItemSelectedListener(new MySelectedListener());
    }

    class MySelectedListener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String[] countryCodeArray = getResources().getStringArray(R.array.public_CountryCodes);
//            showMessage(countryCodeArray[i]);
            phonePreff = countryCodeArray[i];
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }


    private void isPasswordLogin(boolean isPasswordLogin){
        this.isPasswordLogin = isPasswordLogin;
        if (isPasswordLogin){
            user_et_login_ver_code.setText("");
        }else{
            user_et_login_password.setText("");
        }
        user_ll_verification.setVisibility(isPasswordLogin? View.GONE : View.VISIBLE);
        user_ll_password.setVisibility(isPasswordLogin?View.VISIBLE: View.GONE);
        user_tv_ver_code_login.setVisibility(isPasswordLogin?View.VISIBLE: View.GONE);
        user_tv_password_login.setVisibility(isPasswordLogin?View.GONE: View.VISIBLE);
    }

    private void toForgetPassword(){
        ARouter.getInstance().build(RouterHub.USER_RETRIEVEPASSWORDACTIVITY)
                .withString("username",getUserName())
                .navigation(this);
        finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
    private void toRegister() {
        Utils.navigation(this, RouterHub.USER_REGISTERACTIVITY);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
    @Override
    public void onLoginSuccess(User user) {
        showMessage(user.getNickname() + "，欢迎回到启明星~");
        Utils.navigation(this, RouterHub.APP_MAINACTIVITY);
        finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    public int getLoginType() {
        return isPasswordLogin ? 0 : 1;
    }

    @Override
    public String getUserName() {
        return /*phonePreff+*/user_et_login_username.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return user_et_login_password.getText().toString().trim();
    }

    @Override
    public String getSmsCaptcha() {
        return user_et_login_ver_code.getText().toString().trim();
    }

    @Override
    public String getImaCaptcha() {
        return user_et_login_image_code.getText().toString().trim();
    }

    @Override
    public void onImageCap(Bitmap bitmap) {
        user_iv_login_image_code.setImageBitmap(bitmap);

    }

    @Override
    public void getVerCodeUnable(boolean enable, String tips) {
        user_tv_login_ver_code.setEnabled(enable);
        user_tv_login_ver_code.setTextColor(enable? Color.parseColor("#49BA2C"):getResources().getColor(R.color.public_contentTextColorGray));
        user_tv_login_ver_code.setText(tips);
    }


}
